<?php
if(!defined("IICCMS")) exit("Access Denied");
class BaseAction extends Action{
	protected   $Config ,$sysConfig,$categorys,$module,$moduleid,$mod,$dao,$Type,$Role,$_userid,$_groupid,$_email,$_username ,$forward ,$user_menu;
	protected   $province,$city,$area;
    public function _initialize() {
		 	$this->categorys = F('Category');
			$this->Config = F('Config');
			$this->sysConfig = F('sys.config');
			$this->module = F('Module');
			$this->Role = F('Role');
			$this->Type =F('Type');
			$this->assign('Role',$this->Role);
			$this->assign('Type',$this->Type);
	    	$this->province=F("Province");
			$this->city=F("City");
			$this->area=F("Area");
			if(!$this->province){
				savecache('Province');
				$this->province=F("Province");
			}
			if(!$this->city){
				savecache('City');
				$this->city=F("City");
			}
			if(!$this->area){
				savecache('Area');
				$this->area=F("Area");
			}
			//dump($this->province);
			$this->assign("province",$this->province);
			$this->assign($this->Config);
			$this->mod= F('Mod');
			$this->moduleid=$this->mod[MODULE_NAME];
			$this->assign('Module',$this->module);
			$this->assign('Categorys',$this->categorys);
			//dump($this->categorys);
			import("@.ORG.Form");
			$this->assign ( 'form',new Form());
			import("@.TagLib.TagLibIIC");
    		C('PAGE_LISTROWS',$this->sysConfig['PAGE_LISTROWS']);
			C('URL_M',$this->sysConfig['URL_MODEL']);
			C('URL_M_PATHINFO_DEPR',$this->sysConfig['URL_PATHINFO_DEPR']);
			C('URL_M_HTML_SUFFIX',$this->sysConfig['URL_HTML_SUFFIX']);
			//dump($_COOKIE);
			if($_COOKIE['iic_auth']){
				$yourphp_auth_key = sysmd5($this->sysConfig['ADMIN_ACCESS'].$_SERVER['HTTP_USER_AGENT']);
				list($userid,$groupid, $password) = explode("-", authcode($_COOKIE['iic_auth'], 'DECODE', $yourphp_auth_key));
				$this->_userid = $userid;
				$this->_username = $_COOKIE['iic_username'];
				$this->_groupid = $groupid; 
				$this->_email = $_COOKIE['iic_email'];

			}else{
				$this->_groupid = $_COOKIE['iic_groupid']=4;
				$this->_userid =0;
			}
			
			if($_GET['forward'] || $_POST['forward']){	
				$this->forward = $_GET['forward'].$_POST['forward'];
			}else{
				$this->forward =isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] :  $this->Config['site_url'];
			}
			$this->assign('forward',$this->forward);


			foreach((array)$this->module as $r){
				if($r['issearch'])$search_module[$r['name']] = $r['title'];
				if($r['ispost'] && (in_array($this->_groupid,explode(',',$r['postgroup']))))$this->user_menu[$r['id']]=$r;
			}
			$this->assign('search_module',$search_module);
			$this->assign('module_name',MODULE_NAME);
			$this->assign('action_name',ACTION_NAME);
			if(GROUP_NAME=='User'){
				$this->assign('user_menu',$this->user_menu);			
			}
			$this->assign("siteurl",__URL__.'/'.ACTION_NAME);
			$this->assign('ustr',date('YmW'));
	}

    public function index($catid='',$module=''){

		if(empty($catid)) $catid =  intval($_REQUEST['id']);
		$tid =  intval($_REQUEST['tid']);
		$p= max(intval($_REQUEST[C('VAR_PAGE')]),1);
		$sub=list_to_tree($this->categorys,"id","parentid",'_son',$catid);
		$this->assign("sub",$sub);
		
		$cat = $this->categorys[$catid];		
		$bcid = explode(",",$cat['arrparentid']); 
		$bcid = $bcid[1];
		if($bcid == '') $bcid=intval($catid);
		if(empty($module))$module=$cat['module'];
		$this->assign('module_name',$module);
		$left=list_to_tree($this->categorys,"id","parentid",'_son',0);
		foreach ($left as $k=>$v){
			if($v['id']==$bcid){
				$left=$v;
			}
		}
		$this->assign("left",$left);	
		unset($cat['id']);
		$this->assign($cat);
		$cat['id']=$catid;
		$this->assign('catid',$catid);
		$this->assign('bcid',$bcid);
		$fields = F($cat['moduleid'].'_Field');
		foreach($fields as $key=>$r){
			$fields[$key]['setup'] =string2array($fields[$key]['setup']);
		}
		$this->assign ( 'fields', $fields); 
		//Page
		if($module=='Page'){
			$module=M('Page');
			$data = $module->find($catid);
			$seo_title = $cat['title'] ? $cat['title'] : $data['title'];
			$this->assign ('seo_title',$seo_title);
			$this->assign ('seo_keywords',$data['keywords']);
			$this->assign ('seo_description',$data['description']);
			unset($data['id']);

			//分页
			$CONTENT_POS = strpos($data['content'], '[page]');
			if($CONTENT_POS !== false) {			
				$urlrule = geturl($cat,'',$this->Urlrule);
				$urlrule[0] =  urldecode($urlrule[0]);
				$urlrule[1] =  urldecode($urlrule[1]);
				$contents = array_filter(explode('[page]',$data['content']));
				$pagenumber = count($contents);
				for($i=1; $i<=$pagenumber; $i++) {
					$pageurls[$i] = str_replace('{$page}',$i,$urlrule);
				} 
				$pages = content_pages($pagenumber,$p, $pageurls);
				//判断[page]出现的位置
				if($CONTENT_POS<7) {
					$data['content'] = $contents[$p];
				} else {
					$data['content'] = $contents[$p-1];
				}
				$this->assign ('pages',$pages);	
			}

			$template = $cat['template_list'] ? $cat['template_list'] : $cat['module'] ;
			$this->assign ($data);		
			$this->display($template);
		}else{
			$seo_title = $cat['title'] ? $cat['title'] : $cat['catname'];
			$this->assign ('seo_title',$seo_title);
			$this->assign ('seo_keywords',$cat['keywords']);
			$this->assign ('seo_description',$cat['description']);
			$where=array();
			$where['status'] =1;
			if($cat['child']){							
				//$where .= " and catid in(".$cat['arrchildid'].")";
				$where['catid']=array('in',$cat['arrchildid']);
			}else{
				$where['catid'] =$catid;
			}
			$where['tid']=$tid;
			if($module=='Guestbook'){$where['status']=1;}
			if(empty($cat['listtype'])){
				$this->dao= M($module);
				$count = $this->dao->where($where)->count();
				if($count){
					import("@.ORG.ZQPage");
					$listRows =  !empty($cat['pagesize']) ? $cat['pagesize'] : C('PAGE_LISTROWS');
					$page = new ZQPage($count,$listRows,6);
					//$page->urlrule = geturl($cat,'',$this->Urlrule);
					$pages = $page->show();
					$field =  $this->module[$cat['moduleid']]['listfields'];
					$field =  $field ? $field : 'id,catid,userid,url,username,title,title_style,keywords,description,thumb,createtime,hits';
					$list = $this->dao->field($field)->where($where)->order('id desc')->limit($page->firstRow.",$listRows")->select();
					$this->assign('pages',$pages);
					//dump($this->dao->getLastSql());
					$this->assign('list',$list);
				}
				$template_r = '_list';
			}else{
				$template_r = '_index';
			}
			$template = $cat['template_list'] ? $cat['template_list'] : $cat['module'].$template_r;
			$this->display($template);
		}
    }

 

	public function show($id='',$module=''){
		$p= max(intval($_REQUEST[C('VAR_PAGE')]),1);		
		$id = $id ? $id : intval($_REQUEST['id']);
		$module = $module ? $module : MODULE_NAME;
		$this->assign('module_name',$module);
		$this->dao= M($module);;
		$data = $this->dao->find($id);
		if(empty($data)){
			$this->error('您访问的文档不存在！');
		}
		
		$this->assign("info_id",$id);	
		$catid = $data['catid'];		
		$cat = $this->categorys[$data['catid']];		
		$bcid = explode(",",$cat['arrparentid']); 
		$bcid = $bcid[1]; 
		$this->hits(0);
		if($bcid == '') $bcid=intval($catid);
		$left=list_to_tree($this->categorys,"id","parentid",'_son',0);
		foreach ($left as $k=>$v){
			if($v['id']==$bcid){
				$left=$v;
			}
		}
		$this->assign("left",$left);
		dump($data);
		dump($cat);
		if($cat['readgroup'] && !in_array($this->_groupid,explode(',',$cat['readgroup'])))$this->error (L('add_no_postgroup'));	
		
		if($cat['chargepoint']){
			if($data['userid'] !=$this->_userid){
				$user = M('User');
				$userdata =$user->find($this->_userid);
				if($cat['paytype']==1 && $userdata['point']>=$cat['chargepoint']){
					$chargepointok = $user->setDec('point',"id=".$this->_userid,$cat['chargepoint']);
				}elseif($cat['paytype']==2 && $userdata['amount']>=$cat['chargepoint']){
					$chargepointok = $user->setDec('amount',"id=".$this->_userid,$cat['chargepoint']);
				}else{
					$this->error (L('add_no_postgroup'));
				}				
			}
		}
		$seo_title = $data['title'].'-'.$cat['catname'];
		$this->assign ('seo_title',$seo_title);
		$this->assign ('seo_keywords',$data['keywords']);
		$this->assign ('seo_description',$data['description']);
		$this->assign ( 'fields', F($cat['moduleid'].'_Field') );

		$fields = F($this->mod[$module].'_Field');
		foreach($data as $key=>$c_d){
			$setup='';
			$fields[$key]['setup'] =$setup=string2array($fields[$key]['setup']);
			if($setup['fieldtype']=='varchar' && $fields[$key]['type']!='text'){
				$data[$key.'_old_val'] =$data[$key];
				$data[$key]=fieldoption($fields[$key],$data[$key]);
			}elseif($fields[$key]['type']=='images' || $fields[$key]['type']=='files'){ 
				if(!empty($data[$key])){
					$p_data=explode(':::',$data[$key]);
					$data[$key]=array();
					
					foreach($p_data as $k=>$res){
						$p_data_arr=explode('|',$res);					
						$data[$key][$k]['filepath'] = $p_data_arr[0];
						$data[$key][$k]['filename'] = $p_data_arr[1];
					}				
					unset($p_data);
					unset($p_data_arr);
				}
			}
			unset($setup);
		}
		$this->assign('fields',$fields); 
 
		//手动分页
		$CONTENT_POS = strpos($data['content'], '[page]');
		if($CONTENT_POS !== false) {
			
			$urlrule = geturl($cat,$data,$this->Urlrule);
			$urlrule =  str_replace('%7B%24page%7D','{$page}',$urlrule); 
			$contents = array_filter(explode('[page]',$data['content']));
			$pagenumber = count($contents);
			for($i=1; $i<=$pagenumber; $i++) {
				$pageurls[$i] = str_replace('{$page}',$i,$urlrule);
			} 
			$pages = content_pages($pagenumber,$p, $pageurls);
			//判断[page]出现的位置是否在文章开始
			if($CONTENT_POS<7) {
				$data['content'] = $contents[$p];
			} else {
				$data['content'] = $contents[$p-1];
			}
			$this->assign ('pages',$pages);	
		}

		if(!empty($data['template'])){
			$template = $data['template'];
		}elseif(!empty($cat['template_show'])){
			$template = $cat['template_show'];
		}else{
			$template = $cat['module'].'_show';
		}
		
		$this->assign('catid',$catid);
		//dump($data['pics']);
		$this->assign ($cat);
		$this->assign('bcid',$bcid);
 
		$this->assign ($data);
        $this->display($template);	 
    }

	public function down()
	{

		$module = $module ? $module : MODULE_NAME;
		$id = $id ? $id : intval($_REQUEST['id']);
		$this->dao= M($module);
		$filepath = $this->dao->getField('file',"id=".$id);
		$this->dao->setInc('downs',"id=".$id);

		if(strpos($filepath, ':/')) { 
			header("Location: $filepath");
		} else {			
			if(!$filename) $filename = basename($filepath);
			$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
			if(strpos($useragent, 'msie ') !== false) $filename = rawurlencode($filename);
			$filetype = strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
			$filesize = sprintf("%u", filesize($filepath));
			if(ob_get_length() !== false) @ob_end_clean();
			header('Pragma: public');
			header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
			header('Cache-Control: no-store, no-cache, must-revalidate');
			header('Cache-Control: pre-check=0, post-check=0, max-age=0');
			header('Content-Transfer-Encoding: binary');
			header('Content-Encoding: none');
			header('Content-type: '.$filetype);
			header('Content-Disposition: attachment; filename="'.$filename.'"');
			header('Content-length: '.$filesize);
			readfile($filepath);
		}
		exit;
	}

	public function hits($app='1')
	{
		$module = $module ? $module : MODULE_NAME;
		$id = $id ? $id : intval($_REQUEST['id']);
		$this->dao= M($module);
		$this->dao->setInc('hits',"id=".$id);

		if($module=='Download'){
			$r = $this->dao->find($id);
			if($app=='1'){
				echo '$("#hits").html('.$r['hits'].');$("#downs").html('.$r['downs'].');';
			}
		}else{
			$hits = $this->dao->getField('hits',"id=".$id);
			if($app=='1'){
				echo '$("#hits").html('.$hits.');';
			}
		}
		if($app=='1'){
			exit;
		}
	}
    
    /**
	 *展示次数或点击量统计
	 *@date 2010-9-10
	 *@time 上午10:33:46
	 *@param array $arr 资源列表 id 活跃时间 vip开始和结束时间
	 *@param int $click 1:更新点击  2:更新展示
	 */
	protected static function clickorshow($arr=array(), $hits = '1',$model='Tour') {
		//展示次数或点击量统计
		$arc = new Model ( $model );
		$t = time ();
		if ($hits != '1') {
			foreach ( $arr as $v ) {
				$arc->setInc ( 'shownum', "id={$v['id']}", 1 );
			}
		} else {
			$arc->setInc ( 'hits', "id={$arr['id']}", 1 );
			$arc->where("id={$arr['id']}")->setField(array('lasttime'),array($t));
		}
	} //end clickorshow
}
?>